﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Zyg.Utility.Helper;

namespace Zyg.SSO.Web.Admin.Role
{
    public partial class RoleAccounts : Zyg.SSO.Web.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!base.Account.HavePermission(Zyg.SSO.Core.Business.Permission.RoleManage))
                {
                    throw new Exception("你无权查看此页面");
                }
                bool parseSucceed;

                Guid id = Request.QueryString["RoleId"].ToGuid(out parseSucceed);

                if (parseSucceed)
                {
                    BindData(id);
                }
                else
                {
                    throw new Exception("对不起，你所访问的页面不存在");
                }
            }
        }

        private void BindData(Guid roleId)
        {
            Zyg.SSO.Core.Business.Role role = Zyg.SSO.Core.Business.Role.Load(roleId);

            if (roleId == null)
            {
                throw new Exception("对不起，你所访问的页面不存在");
            }

            RoleName.Text = role.Name;

            IList<Zyg.SSO.Core.Business.Account> accounts = Zyg.SSO.Core.Business.Account.GetAccounts(
                String.Empty,
                String.Empty,
                Zyg.SSO.Core.Business.AccountState.Active,
                true,
                roleId,
                new Nullable<DateTime>(),
                new Nullable<DateTime>(),
                new Nullable<int>(),
                new Nullable<int>());

            GridViewRoleAccounts.DataSource = Zyg.SSO.Core.Business.Account.ToDataTable(accounts);
            GridViewRoleAccounts.DataBind();
        }

        protected void BtnDelete_Click(object sender, EventArgs e)
        {
            bool parseSucceed;

            Guid id = Request.QueryString["RoleId"].ToGuid(out parseSucceed);

            Zyg.SSO.Core.Business.Role role = Zyg.SSO.Core.Business.Role.Load(id);

            if (role == null)
                return;

            for (int i = GridViewRoleAccounts.Rows.Count - 1; i > -1; i--)
            {
                CheckBox cb = GridViewRoleAccounts.Rows[i].FindControl("CBSelect") as CheckBox;

                if (cb != null && cb.Checked)
                {
                    string userId = GridViewRoleAccounts.DataKeys[i].Value as string;

                    role.Accounts.DeleteOnSave(new Guid(userId));
                }
            }

            role.Save();

            BindData(id);
        }
    }
}
